<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="运费模板名称" prop="transName">
        <el-input
          v-model="queryParams.transName"
          placeholder="请输入运费模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="是否包邮 0:不包邮 1:包邮" prop="isFreeFee">
        <el-input
          v-model="queryParams.isFreeFee"
          placeholder="请输入是否包邮 0:不包邮 1:包邮"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:transport:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:transport:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:transport:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:transport:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="运费模板id" align="center" prop="transportId" />
      <el-table-column label="运费模板名称" align="center" prop="transName"/>
      <el-table-column label="收费方式" align="center" prop="chargeType"  :formatter="transportTypeFormatter"/>
      <el-table-column label="是否包邮 0:不包邮 1:包邮" align="center" prop="isFreeFee" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:transport:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:transport:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运费模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="模板名称"
                      prop="transName"
                      :rules="[
                      { required: true, message: '模板名称不能为空'},
                      { pattern: /\s\S+|S+\s|\S/, message: '请输入正确的模板名称', trigger: 'blur' }
                    ]">
          <el-input v-model="form.transName"
                    placeholder="模板名称"></el-input>
        </el-form-item>
        <el-form-item label="模板类型"
                      prop="isFreeFee"
                      required="required">
          <template>
            <el-radio-group v-model="form.isFreeFee"
                            @change="changeFreeFee">
              <el-radio :label="0">买家承担运费</el-radio>
              <el-radio :label="1">卖家包邮</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item label="收费方式"
                      prop="chargeType">
          <template>
            <el-radio-group v-model="form.chargeType"
                            :disabled="form.isFreeFee == 1">
              <el-radio :label="0">按件数</el-radio>
              <el-radio :label="1">按重量</el-radio>
              <el-radio :label="2">按体积</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-table :data="form.transfees"
                  border
                  style="width: 100%;"
                  class="table-con"
        >
          <el-table-column header-align="center"
                           align="center"
                           width="150"
                           label="可配送区域">
            <template slot-scope="scope">
              <span v-if="scope.$index == 0">所有地区</span>
              <span v-if="(!scope.row.cityList || !scope.row.cityList.length) && scope.$index > 0">请选择可配送区域</span>
              <span v-if="scope.$index > 0">
              <el-tag v-for="city in scope.row.cityList"
                      :key="city.areaId"
              >{{city.areaName}}</el-tag>
            </span>
              <el-button v-if="scope.$index > 0"
                         type="text"
                         size="small"
                         @click="addOrUpdateHandle(`${scope.$index}`)">编辑</el-button>
              <el-button v-if="scope.$index > 0"
                         type="text"
                         size="small"
                         @click="deleteHandle(`${scope.$index}`)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column header-align="center"
                           align="center"
                           width="180"
                           :label="tableTitle[0]">
            <template slot-scope="scope">
              <el-form-item :prop="`transfees.${scope.$index}.firstPiece`"
                            label-width="0px"
                            :rules="[{ required: true, message: `${tableTitle[0]}不能为空`}]">
                <el-input type="number"
                          @change="checkNumber(scope.row, 1)"
                          v-model="scope.row.firstPiece"
                          :disabled="!scope.row.status && scope.$index === 0"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column header-align="center"
                           align="center"
                           :label="tableTitle[1]">
            <template slot-scope="scope">
              <el-form-item :prop="`transfees.${scope.$index}.firstFee`"
                            label-width="0px"
                            :rules="[{ required: true, message: `${tableTitle[1]}不能为空`}]">
                <el-input type="number"
                          v-model="scope.row.firstFee"
                          :disabled="!scope.row.status && scope.$index === 0"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column header-align="center"
                           align="center"
                           :label="tableTitle[2]">
            <template slot-scope="scope">
              <el-form-item :prop="`transfees.${scope.$index}.continuousPiece`"
                            label-width="0px"
                            :rules="[{ required: true, message: `${tableTitle[2]}不能为空`}]">
                <el-input type="number"
                          @change="checkNumber(scope.row, 3)"
                          v-model="scope.row.continuousPiece"
                          :disabled="!scope.row.status && scope.$index === 0"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column header-align="center"
                           align="center"
                           :label="tableTitle[3]">
            <template slot-scope="scope">
              <el-form-item :prop="`transfees.${scope.$index}.continuousFee`"
                            label-width="0px"
                            :rules="[{ required: true, message: `${tableTitle[3]}不能为空`}]">
                <el-input type="number"
                          v-model="scope.row.continuousFee"
                          :disabled="!scope.row.status && scope.$index === 0"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>

<!--        <el-form-item label="运费模板名称" prop="transName">-->
<!--          <el-input v-model="form.transName" placeholder="请输入运费模板名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="店铺id" prop="shopId">-->
<!--          <el-input v-model="form.shopId" placeholder="请输入店铺id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否包邮 0:不包邮 1:包邮" prop="isFreeFee">-->
<!--          <el-input v-model="form.isFreeFee" placeholder="请输入是否包邮 0:不包邮 1:包邮" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否含有包邮条件 0 否 1是" prop="hasFreeCondition">-->
<!--          <el-input v-model="form.hasFreeCondition" placeholder="请输入是否含有包邮条件 0 否 1是" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTransport, getTransport, delTransport, addTransport, updateTransport } from "@/api/system/transport";

export default {
  name: "Transport",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运费模板表格数据
      transportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transName: null,
        shopId: null,
        chargeType: null,
        isFreeFee: null,
        hasFreeCondition: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
    computed:{
        tableTitle (){
            var titles = [['首件(个)', '运费(元)', '续件(个)', '续费(元)'], ['首重(kg)', '运费(元)', '续重(kg)', '续费(元)'], ['首体积(m³)', '运费(元)', '续体积(m³)', '续费(元)']]
            if (this.form.chargeType) {
                return titles[this.form.chargeType]
            }
            return titles[0]
        }
    },
  created() {
    this.getList();
  },
  methods: {
    /** 查询运费模板列表 */
    getList() {
      this.loading = true;
      listTransport(this.queryParams).then(response => {
        this.transportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        // transportId: null,
        // transName: null,
        // createTime: null,
        // shopId: null,
        // chargeType: null,
        // isFreeFee: null,
        // hasFreeCondition: null

          hasFreeCondition: null,
          transName: '',
          createTime: '',
          chargeType: 0,
          transportId: null,
          isFreeFee: 0,
          transfees: [{ cityList: [], status: 1 }],
          transfeeFrees: [{ freeCityList: [], freeType: 0 }]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.transportId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加运费模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const transportId = row.transportId || this.ids
      getTransport(transportId).then(response => {
        this.open = true;
        this.title = "修改运费模板";

          if (response.data.isFreeFee) {
              response.data.transfees[0].status = 0
          } else {
              response.data.transfees[0].status = 1
          }
          this.form = response.data;

          this.form.hasFreeCondition = !!response.data.hasFreeCondition

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.transportId != null) {
            updateTransport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTransport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const transportIds = row.transportId || this.ids;
      this.$modal.confirm('是否确认删除运费模板编号为"' + transportIds + '"的数据项？').then(function() {
        return delTransport(transportIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/transport/export', {
        ...this.queryParams
      }, `transport_${new Date().getTime()}.xlsx`)
    },
      transportTypeFormatter(row,col){
          if(row.chargeType == 0){
              return '按件'
          }else if(row.chargeType == 1){
              return '按重量'
          }else{
              return '按体积'
          }
      },
      // 改变模板类型， 0 买家承担运费 1 卖家包邮
      changeFreeFee (val) {
          this.form.hasFreeCondition = 0
          if (val) {
              this.form.chargeType = 0
              this.form.transfees = [{ cityList: [], status: 0, firstPiece: 1, firstFee: 0, continuousPiece: 1, continuousFee: 0 }]
          } else {
              this.form.transfees = [{ cityList: [], status: 1 }]
          }
      },
      /**
       * 校验输入的数字
       */
      checkNumber (row, type) {
          if (type === 1) {
              row.firstPiece = this.getNumber(row.firstPiece)
              row.firstPiece = row.firstPiece === 0 ? 1 : row.firstPiece
          } else if (type === 3) {
              row.continuousPiece = this.getNumber(row.continuousPiece)
              row.continuousPiece = row.continuousPiece === 0 ? 1 : row.continuousPiece
          }
      },
      /**
       * 保留整数并小于零的数设为0
       */
      getNumber (num) {
          num = Math.round(num)
          return num < 0 ? 0 : num
      }
  }
};
</script>
